﻿using OfficeHelper;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using Tencent;

namespace xyjc
{
    /// <summary>
    /// 内置函数类
    /// </summary>
    class AppBuiltInFuncs : IBuiltInFuncs
    {
        private AppConfig Config { get; set; }
        public AppBuiltInFuncs(AppConfig appConfig)
        {
            Config = appConfig;
        }

        public string RunFunc(string funcName, string[] paramValues)
        {
            string value = "";
            switch (funcName)
            {
                case "GetRiskValues":
                    {
                        value = GetRiskValues(paramValues);
                        break;
                    }
                case "CreateRiskPic":
                    {
                        value = CreateRiskPic(paramValues);
                        break;
					}
				case "SubStr":
					{
						value = SubStr(paramValues);
						break;
					}
				case "ArrayOf":
                    {
                        value = ArrayOf(paramValues);
                        break;
                    }
                case "Arrow":
                    {
                        value = Arrow(paramValues);
                        break;
                    }
                case "Arrow2":
                    {
                        value = Arrow2(paramValues);
                        break;
                    }
            }
            return value;
        }

		private string SubStr(string[] paramValues)
		{
			string str = paramValues[0];
			int begin = int.Parse(paramValues[1]);
			int len = int.Parse(paramValues[2]);

			string result = str;
			if (begin >= 0 && begin < str.Length && len >= 0 && len <= str.Length)
			{
				result = str.Substring(begin, len);
			}
			return result;
		}

        // 得到数组中的某一个元素，数组为用逗号分隔的元素集合
        private string ArrayOf(string[] paramValues)
        {
            string arrStr = paramValues[0];
            int index = int.Parse(paramValues[1]);
            string[] arr = arrStr.Split(',');
            return arr[index];
        }

        // 根据图片得到风险值数组
        private string GetRiskValues(string[] paramValues)
        {
            // 解析图片中的文字
            string imageFileName = paramValues[0];
            string base64Image = TencentOCR.ImageToBase64(imageFileName);
            TencentOCR ocr = new TencentOCR("1252867739", "AKIDcAe3HJs1c1FKEwD2LTPDptpaBcs0viqo", "wiIwb9Zs361viNuKgwdu7DC6udkqphZQ");
            GeneralResponse res = ocr.General(base64Image);

            // 将百分比提取出来，得到数组
            string content = "";
            foreach (DataItem item in res.data.items)
            {
                content += item.itemstring;
            }

            string pattern = @"\=\s*(\d+)\s*\%";
            var matches = Regex.Matches(content, pattern);

            List<string> list = new List<string>();
            foreach (Match match in matches)
            {
                list.Add(match.Groups[1].Value);
            }

            string result = string.Join(",", list.ToArray());

            return result;
        }

        // 根据风险值数组创建新的风险图片
        private string CreateRiskPic(string[] paramValues)
        {
            var values = paramValues[0].Split(',');

            Image imgTemp = new Bitmap("BaseTemplate/risk.png");
            Graphics g = Graphics.FromImage(imgTemp);

            List<SolidBrush> levels = new List<SolidBrush>();
            levels.Add(new SolidBrush(Color.FromArgb(143, 195, 31)));
            levels.Add(new SolidBrush(Color.FromArgb(0, 162, 154)));
            levels.Add(new SolidBrush(Color.FromArgb(243, 152, 0)));
            levels.Add(new SolidBrush(Color.FromArgb(195, 13, 35)));
            levels.Add(new SolidBrush(Color.FromArgb(96, 25, 134)));
            levels.Add(new SolidBrush(Color.FromArgb(96, 25, 134)));

            for (int i = 0; i < values.Length; i++)
            {
                int temp = int.Parse(values[i]);
                int level = (int)(temp / 20);
                int x = 12 + i * 33;
                int height = (int)(205 * temp / 100);
                int y = 245 - height;
                int width = 16;
                g.FillRectangle(levels[level], x, y, width, height);
            }

            string path = Utils.GetPictruePath(Config.FileSavePath);
            imgTemp.Save(path);
            g.Dispose();
            return path;
        }

        private string ParaOf(string[] paramValues)
        {
            string parasStr = paramValues[0];
            string[] paras = parasStr.Split('\n');
            int beginIndex = int.Parse(paramValues[1]);
            int endIndex = int.Parse(paramValues[2]);
            if (endIndex == 0) endIndex = paras.Length;
            string result = "";
            for(int i = beginIndex; i < endIndex; i++)
            {
                result += paras[i] + "\n";
            }
            return result;
        }

        private string Arrow(string[] paramValues)
        {
            int value = int.Parse(paramValues[0].Trim());
            string result = "";
            if (value > -20 && value < 20)
            {
                
            }
            else
            {
                string color, arrow;
                int temp = (Math.Abs(value) / 20);
                if (value > 0)
                {
                    color = "green";
                    arrow = new string('↑', temp);
                }
                else
                {
                    color = "red";
                    arrow = new string('↓', temp);
                }

                result = DocConvert.CreateElement("span", new Dictionary<string, string> {
                    { "style", DocConvert.StyleToStr(new Dictionary<string, string>{
                        { "color", color }
                    }) }
                }, arrow);
            }
            return result;
        }

        private string Arrow2(string[] paramValues)
        {
            int step = int.Parse(paramValues[0].Trim());
            int value = 0;
            if(!int.TryParse(paramValues[1].Trim(), out value))
            {
                return "";
            }
            string result = "";
            if (value > -step && value < step)
            {

            }
            else
            {
                string color, arrow;
                int temp = (Math.Abs(value) / step);
                if (value > 0)
                {
                    color = "green";
                    arrow = new string('↑', 1);
                }
                else
                {
                    color = "red";
                    arrow = new string('↓', 1);
                }

                result = DocConvert.CreateElement("span", new Dictionary<string, string> {
                    { "style", DocConvert.StyleToStr(new Dictionary<string, string>{
                        { "color", color }
                    }) }
                }, arrow);
            }
            return result;
        }
    }
}
